package com.ruoyi.scheduling.service.impl;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.scheduling.domain.ADispatchRequests;
import com.ruoyi.scheduling.domain.ASchedulingExecutionVehicle;
import com.ruoyi.scheduling.dto.ADispatchExecutionsDTO;
import com.ruoyi.scheduling.mapper.ADispatchRequestsMapper;
import com.ruoyi.scheduling.mapper.ASchedulingExecutionVehicleMapper;
import com.ruoyi.system.api.RemoteVehiclesService;
import com.ruoyi.system.api.domain.SysVechicleDto;
import com.ruoyi.system.api.domain.SysVehicles;
import com.ruoyi.system.api.domain.UpdateUseUnitDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.scheduling.mapper.ADispatchExecutionsMapper;
import com.ruoyi.scheduling.domain.ADispatchExecutions;
import com.ruoyi.scheduling.service.IADispatchExecutionsService;

/**
 * 调度执行Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-04-02
 */
@Service
public class ADispatchExecutionsServiceImpl implements IADispatchExecutionsService 
{
    @Autowired
    private ADispatchExecutionsMapper aDispatchExecutionsMapper;

    @Autowired
    private ADispatchRequestsMapper aDispatchRequestsMapper;

    @Autowired
    private ASchedulingExecutionVehicleMapper aSchedulingExecutionVehicleMapper;

    @Autowired
    private RemoteVehiclesService remoteVehiclesService;


    /**
     * 查询调度执行
     * 
     * @param id 调度执行主键
     * @return 调度执行
     */
    @Override
    public ADispatchExecutionsDTO selectADispatchExecutionsById(Long id)
    {
        //查询调度执行记录详情
        ADispatchExecutions aDispatchExecutions = aDispatchExecutionsMapper.selectADispatchExecutionsId(id);
        if (aDispatchExecutions == null) {
            throw new RuntimeException("未找到该申请订单");
        }
        System.out.println(aDispatchExecutions);
        //查询关联的车辆调度申请
        List<ASchedulingExecutionVehicle> aSchedulingExecutionVehicles = aSchedulingExecutionVehicleMapper.selectASchedulingExecutionVehicleBySchedulingApplicationId(String.valueOf(id), 2L);
        if (aSchedulingExecutionVehicles.isEmpty()) {
            throw new RuntimeException("未找到该申请订单");
        }
        Set<SysVehicles> sysVehiclesFromExecutionVehicles = this.getSysVehiclesFromExecutionVehicles(aSchedulingExecutionVehicles);
        R<Set<SysVechicleDto>> setR = remoteVehiclesService.selectVehicles(sysVehiclesFromExecutionVehicles);
        if (setR.getCode() != 200) {
            throw new RuntimeException("有车辆信息未找到");
        }
        ADispatchExecutionsDTO aDispatchExecutionsDTO = new ADispatchExecutionsDTO();
        BeanUtil.copyProperties(aDispatchExecutions, aDispatchExecutionsDTO);
        aDispatchExecutionsDTO.setSysVechicleDto(setR.getData());
        return aDispatchExecutionsDTO;
    }

    private Set<SysVehicles> getSysVehiclesFromExecutionVehicles(List<ASchedulingExecutionVehicle> aSchedulingExecutionVehicles) {
        Set<SysVehicles> sysVehicles = new HashSet<>();
        for (ASchedulingExecutionVehicle aSchedulingExecutionVehicle : aSchedulingExecutionVehicles) {
            SysVehicles sysVehicle = new SysVehicles();
            sysVehicle.setId(aSchedulingExecutionVehicle.getVehicleId());
            sysVehicles.add(sysVehicle);
        }
        return sysVehicles;
    }

    /**
     * 查询调度执行列表
     * 
     * @param aDispatchExecutions 调度执行
     * @return 调度执行
     */
    @Override
    public List<ADispatchExecutions> selectADispatchExecutionsList(ADispatchExecutions aDispatchExecutions)
    {
        return aDispatchExecutionsMapper.selectADispatchExecutionsList(aDispatchExecutions);
    }

    /**
     * 用户取车
     * 
     * @param aDispatchExecutions 调度执行
     * @return 结果
     */
    @Override
    public int insertADispatchExecutions(ADispatchExecutions aDispatchExecutions)
    {
        // 检查调度请求ID是否为空
        if (aDispatchExecutions.getDispatchRequestsId() == null) {
            throw new RuntimeException("调度请求id不能为空");
        }
        // 查询调度请求详情
        ADispatchRequests aDispatchRequests = aDispatchRequestsMapper.selectAApprovalRequestsId(aDispatchExecutions.getDispatchRequestsId());
        if (aDispatchRequests == null) {
            throw new RuntimeException("不存在该申请,请去提交申请");
        }
        // 获取当前时间并格式化
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = now.format(formatter);
        // 获取车辆信息并设置状态为执行中
        List<ASchedulingExecutionVehicle> aSchedulingExecutionVehicles = aSchedulingExecutionVehicleMapper.selectASchedulingExecutionVehicleBySchedulingApplicationId(aDispatchExecutions.getDispatchRequestsId(), 1L);
        Set<SysVehicles> sysVehicles=new HashSet<>();
        for (ASchedulingExecutionVehicle aSchedulingExecutionVehicle : aSchedulingExecutionVehicles){
            SysVehicles sysVehicle = new SysVehicles();
            sysVehicle.setId(aSchedulingExecutionVehicle.getVehicleId());
            sysVehicle.setStatus(0L);
            sysVehicles.add(sysVehicle);
            aSchedulingExecutionVehicle.setType(2L);
        }
        System.out.println(aSchedulingExecutionVehicles);
        System.out.println(sysVehicles);

        // 调用远程服务更新车辆状态
//        AjaxResult ajaxResult = remoteVehiclesService.updateStatus(sysVehicles);
//        if (200 != (int) ajaxResult.get("code")) {
//            throw new RuntimeException("有车辆预约失败");
//        }
        // 调用远程服务更新车辆状态
        // 调用远程服务更新车辆使用单位
        UpdateUseUnitDTO updateUseUnitDTO = new UpdateUseUnitDTO();
        updateUseUnitDTO.setSysVehicles(sysVehicles);
        updateUseUnitDTO.setCallingOrganizationId(aDispatchRequests.getCallingOrganizationId());
        AjaxResult ajaxResult1 = remoteVehiclesService.updateUseUnit(updateUseUnitDTO);
        if (200 != (int) ajaxResult1.get("code")) {
            throw new RuntimeException("有车辆预约失败");
        }
        // 构建申请执行记录对象
        aDispatchExecutions.setActualCallTime(formattedDateTime);
        aDispatchExecutions.setCallingOrganizationId(aDispatchRequests.getCallingOrganizationId());
        aDispatchExecutions.setCallingOrganizationName(aDispatchRequests.getCallingOrganizationName());
        aDispatchExecutions.setCalledOrganizationId(aDispatchRequests.getCalledOrganizationId());
        aDispatchExecutions.setCalledOrganizationName(aDispatchRequests.getCalledOrganizationName());

        // 插入车辆调度申请
        int i = aSchedulingExecutionVehicleMapper.insertASchedulingExecutionVehicleId(aSchedulingExecutionVehicles);
        if (i != aSchedulingExecutionVehicles.size()) {
            throw new RuntimeException("有车辆预约失败");
        }

        // 插入申请执行记录
        int i1 = aDispatchExecutionsMapper.insertADispatchExecutions(aDispatchExecutions);
        if (i1 != 1) {
            throw new RuntimeException("执行失败，请联系管理员");
        }

        // 更新审批请求状态
        aDispatchRequests.setDispatchRequestsStatus(3L);
        int i2 = aDispatchRequestsMapper.updateADispatchRequests(aDispatchRequests);
        if (i2 != 1) {
            throw new RuntimeException("执行失败，请联系管理员");
        }

        return i1;
    }

    /**
     * 修改调度执行
     * 
     * @param aDispatchExecutions 调度执行
     * @return 结果
     */
    @Override
    public int updateADispatchExecutions(ADispatchExecutions aDispatchExecutions)
    {
        return aDispatchExecutionsMapper.updateADispatchExecutions(aDispatchExecutions);
    }

    /**
     * 批量删除调度执行
     * 
     * @param ids 需要删除的调度执行主键
     * @return 结果
     */
    @Override
    public int deleteADispatchExecutionsByIds(Long[] ids)
    {
        return aDispatchExecutionsMapper.deleteADispatchExecutionsByIds(ids);
    }

    /**
     * 删除调度执行信息
     * 
     * @param id 调度执行主键
     * @return 结果
     */
    @Override
    public int deleteADispatchExecutionsById(Long id)
    {
        // 查询审批请求详情
        ADispatchRequests aDispatchRequests = aDispatchRequestsMapper.selectADispatchRequestsId(id);
        if (aDispatchRequests == null) {
            throw new RuntimeException("不存在该申请,请去提交申请");
        }

        ADispatchExecutions aDispatchExecutions=aDispatchExecutionsMapper.selectADispatchExecutionsId(id);
        if (aDispatchExecutions==null){
            throw new RuntimeException("该执行记录不存在");
        }

        // 查询关联的车辆调度申请
        List<ASchedulingExecutionVehicle> aSchedulingExecutionVehicles = aSchedulingExecutionVehicleMapper.selectASchedulingExecutionVehicleBySchedulingApplicationId(String.valueOf(id), 2L);
        if (aSchedulingExecutionVehicles.isEmpty()) {
            throw new RuntimeException("未找到该执行记录");
        }

        // 获取车辆信息并设置状态为空闲
        Set<SysVehicles> sysVehicles=new HashSet<>();
        for (ASchedulingExecutionVehicle aSchedulingExecutionVehicle : aSchedulingExecutionVehicles){
            SysVehicles sysVehicle = new SysVehicles();
            sysVehicle.setId(aSchedulingExecutionVehicle.getVehicleId());
            sysVehicle.setStatus(0L);
            sysVehicles.add(sysVehicle);
        }
        AjaxResult ajaxResult = remoteVehiclesService.removeUseUnit(sysVehicles);
        if (200 != (int) ajaxResult.get("code")) {
            throw new RuntimeException("有车辆预约失败");
        }

        // 获取当前时间并格式化
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = now.format(formatter);

        // 更新申请执行记录状态
        aDispatchExecutions.setActualEndTime(formattedDateTime);
        int i = aDispatchExecutionsMapper.updateADispatchExecutions(aDispatchExecutions);
        if (i != 1) {
            throw new RuntimeException("执行失败，请联系管理员");
        }
        // 更新调度请求状态
        aDispatchRequests.setDispatchRequestsStatus(4L);
        int i2 = aDispatchRequestsMapper.updateADispatchRequests(aDispatchRequests);
        if (i2 != 1) {
            throw new RuntimeException("执行失败，请联系管理员");
        }
        return i;
    }
}
